package com.zt.teacher.service.impl;

import com.zt.common.Do.ActiveClassDO;
import com.zt.common.Do.PrivateLetterDO;
import com.zt.common.Do.PrivateLetterWithInfoDO;
import com.zt.common.pojo.ActiveClass;
import com.zt.common.pojo.PrivateLetter;
import com.zt.common.pojo.StudentVx;
import com.zt.common.pojo.netty.Sender;
import com.zt.common.pojo.origin.OriginStudent;
import com.zt.common.utils.JwtUtil;
import com.zt.teacher.dao.PrivateLetterDao;
import com.zt.teacher.dto.PrivateLetterDTO;
import com.zt.teacher.dto.PrivateLetterDetailDTO;
import com.zt.teacher.dto.StudentInfoDTO;
import com.zt.teacher.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * description:
 * author:zt
 * date:2022-02-06
 */
@Service
@Transactional
public class PrivateLetterServiceImpl implements PrivateLetterService {

    @Autowired
    private PrivateLetterDao privateLetterDao;
    @Autowired
    private ClassSelectionService classSelectionService;
    @Autowired
    private ActiveClassService activeClassService;

    @Override
    public ArrayList<PrivateLetterWithInfoDO> getRecord(HttpServletRequest request, String semester){
        //获取当前登录用户id
        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));
        ArrayList<PrivateLetterWithInfoDO> list = new ArrayList<>();
        //该老师所上的课的所有学生信息
        HashSet<StudentInfoDTO> set = new HashSet<>();

        //获取老师指定学期所有的课
        List<ActiveClass> classes = activeClassService.getClassByTeacherId(semester, request);
        //遍历课堂信息存放学生信息
        classes.forEach(c -> set.addAll(classSelectionService.getStuInfoByClassId(c.getId())));

        for (StudentInfoDTO student : set) {
            //获取当前用户与该老师最近10条消息
            List<PrivateLetter> letterLists = privateLetterDao.select(teacherId, student.getId());
            //如果没有聊天记录则跳过
            if (letterLists == null || letterLists.size()==0) continue;

            //关联聊天对方的身份信息（id、名字、头像、所属activeCLass）
            ArrayList<ActiveClassDO> activeClassDOS = new ArrayList<>();
            activeClassService.getClassByTeaAndStuId(request, student.getId(), semester).forEach(a -> {
                activeClassDOS.add(new ActiveClassDO(a.getId(),a.getName()));
            });
            PrivateLetterWithInfoDO privateLetterWithInfoDO = new PrivateLetterWithInfoDO();
            privateLetterWithInfoDO.setUserId(student.getId()).setName(student.getName()).setAvatar(student.getAvatar()).setActiveClassDOS(activeClassDOS);

            ArrayList<PrivateLetterDO> privateLetterDOS = new ArrayList<>();

            letterLists.forEach(l -> {
                if (l.getSenderId().equals(teacherId))
                    //自己是发送方
                    privateLetterDOS.add(new PrivateLetterDO(l.getMessage(),l.getSendTime(),0,l.getStatus()));
                else
                    //自己是接收方
                    privateLetterDOS.add(new PrivateLetterDO(l.getMessage(),l.getSendTime(),1,l.getStatus()));
            });
            privateLetterWithInfoDO.setPrivateLetterDOS(privateLetterDOS);
            list.add(privateLetterWithInfoDO);
        }

        //根据每个聊天的最新消息发送时间进行排序 最新的消息时间最近的排前
        list.sort(new Comparator<PrivateLetterWithInfoDO>() {
            DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            @Override
            public int compare(PrivateLetterWithInfoDO a, PrivateLetterWithInfoDO b) {
                return b.getPrivateLetterDOS().get(0).getSendTime().compareTo(a.getPrivateLetterDOS().get(0).getSendTime());
            }
        });
        return list;
    }

    @Override
    public String insert(PrivateLetterDTO privateLetterDTO, HttpServletRequest request){
        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));
        Date date = new Date();
        privateLetterDao.insert(teacherId,privateLetterDTO.getMessage(),0, date,privateLetterDTO.getReceiverIds());

        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     * @param request 学生学号
     * @param privateLetterDetailDTO 聊天另一方id及截至时间
     * @return 获取截至时间前的10条消息
     */
    @Override
    public List<PrivateLetterDO> getDetail(HttpServletRequest request, PrivateLetterDetailDTO privateLetterDetailDTO){
        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));

        List<PrivateLetter> detail = privateLetterDao.getDetail(teacherId, privateLetterDetailDTO.getUserId(), privateLetterDetailDTO.getTime());
        ArrayList<PrivateLetterDO> list = new ArrayList<>();

        for (PrivateLetter letter : detail) {
            list.add(new PrivateLetterDO(letter.getMessage(), letter.getSendTime(), teacherId.equals(letter.getSenderId())?0:1, letter.getStatus()));
        }
        return list;
    }

    /**
     * 读取消息 修改消息状态
     */
    @Override
    public void readLetter(HttpServletRequest request,PrivateLetterDetailDTO privateLetterDetailDTO){
        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));

        privateLetterDao.readLetter(privateLetterDetailDTO.getUserId(), teacherId, privateLetterDetailDTO.getTime());
    }

    @Override
    public int getUnreadCount(HttpServletRequest request, String semester) {
        String teacherId = JwtUtil.decodedGetID(request.getHeader("Authorization"));
        return privateLetterDao.getUnreadCount(teacherId,semester);
    }
}
